<template>
  <a-dropdown placement="bottomRight">
    <i class="iconfont icon-language" style="font-size: 20px"> </i>
    <span v-if="showText" class="ml-1">{{ getLocaleText }}</span>
    <template #overlay>
      <a-menu v-model:selectedKeys="selectedKeys" @click="handleMenuClick">
        <a-menu-item v-for="item in localeList" :key="item.lang">
          <a href="javascript:;">{{ item.icon }} {{ item.label }}</a>
        </a-menu-item>
      </a-menu>
    </template>
  </a-dropdown>
</template>
<script lang="ts" setup>
import { ref, watchEffect, unref, computed, onMounted, } from 'vue';
import { useLocale } from '@/locales/useLocale';
import { type LocaleType, localeList } from '@/locales/config';

const props = defineProps({
  /**
   * Whether to display text
   */
  showText: { type: Boolean, default: true },
  /**
   * Whether to refresh the interface when changing
   */
  reload: { type: Boolean },
});

const selectedKeys = ref<string[]>([]);

const { changeLocale, getLocale } = useLocale();

const getLocaleText = computed(() => {
  const key = selectedKeys.value[0];
  if (!key) {
    return '';
  }
  return localeList.find((item) => item.lang === key)?.label;
});

watchEffect(() => {
  selectedKeys.value = [unref(getLocale)];
});

async function toggleLocale(lang: LocaleType | string) {
  await changeLocale(lang as LocaleType);
  selectedKeys.value = [lang as string];
  props.reload && location.reload();
}

function handleMenuClick({ key }: { key: string }) {
  if (unref(getLocale) === key) {
    return;
  }
  toggleLocale(key as string);
}
//onMounted
onMounted(() => {

})
</script>

<style lang="less" scoped></style>

